package com.jinlejia.erp.widget.image;

import android.app.Activity;
import android.content.Context;
import androidx.fragment.app.Fragment;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.jinlejia.erp.BuildConfig;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DbUtil;
import com.jinlejia.erp.utils.RxUpLoad;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.LubanZ;

/**
 * 图片上传
 */

public final class UploadHelper {
    private volatile Host host;
    public UploadHelper(Context context){
        this.host = Host.create(context);
    }
    public UploadHelper(Fragment fragment){
        this.host = Host.create(fragment);
    }

    public static void toSelectSingleImage(Activity activity,int pictureRequestCode){
        ImageSelector.builder()
                .useCamera(true)
                .setMaxSelectCount(1)
//                .setSelected(cachePicture)
                .setViewImage(true)
                .start(activity, pictureRequestCode);
    }


    public static void toSelectSingleImage(Fragment fragment, int pictureRequestCode){
        ImageSelector.builder()
                .useCamera(true)
                .setMaxSelectCount(1)
//                .setSelected(cachePicture)
                .setViewImage(true)
                .start(fragment, pictureRequestCode);
    }

    public interface UploadCallBack{
        void uploadSuccess(String url);
        void uploadFailed();
    }

    public void upload(String imageUrl, final UploadCallBack callBack){
        if (!host.isAlive())return; //如果页面已经销毁，则返回不做操作
        if (BuildConfig.DEBUG){
            callBack.uploadSuccess(imageUrl);
            return;
        }
        ArrayList<LubanZ.LubanZImage> list = new ArrayList<>(1);
        LubanZ.LubanZImage zImage = new LubanZ.LubanZImage();
        File file = new File(imageUrl);
        if (!file.exists())return; //如果文件不存在，则返回
        zImage.setOriginalFile(file);
        list.add(zImage);
        LubanZ.get(host.context())
                .load(list)
                .asObservable()
                .flatMap(new Func1<LubanZ.LubanZImage, Observable<String>>() {
                    @Override
                    public Observable<String> call(LubanZ.LubanZImage lubanZImage) {
                        if (host.isAlive())return null;
                        Context context = host.context();
                        Map<String, String> header = new HashMap<>();
                        header.put("token", ACache.get(context).getAsString("token") == null ? ""
                                : ACache.get(context).getAsString("token"));
                        header.put("cookie", null == DbUtil.getDB(context).single()
                                .queryById(200, SaveCookieBean.class) ? ""
                                : DbUtil.getDB(context)
                                .single()
                                .queryById(200, SaveCookieBean.class).getCookie());
                        File file = lubanZImage.getThumbFile();
                        File originalFile = lubanZImage.getOriginalFile();
                        if (file.length()>=5242880){ //当文件超过或等于5M时，抛出异常
                            throw new IllegalArgumentException("文件过大");
                        }
                        String fileName = URLEncoder.encode(originalFile.getPath());
                        return RxUpLoad.get(context)
                                .url(ApiConfig.IMG_UPLOAD_2)
                                .file(file)
                                .fileName(fileName)
                                .key("uploadFileNew")
                                .header(header)
                                .asObservable();
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {

                    @Override
                    public void onCompleted() {
                        callBack.uploadFailed();
                    }

                    @Override
                    public void onError(Throwable e) {
                        callBack.uploadFailed();
                    }

                    @Override
                    public void onNext(String s) {
                        callBack.uploadSuccess(s);
                    }
                });

    }

}
